﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using ChBusiness.User;
using ChBusiness.Common;
using Common.Log;
using System.IO;
using WF_Business;

namespace ChBusiness.InterfaceClass
{
    /// <summary>
    /// 用户同步
    /// </summary>
    public class UserTbOperation
    {
        /// <summary>
        /// 分析xml数据并形成数据集
        /// </summary>
        /// <param name="strXml">xml文件内容</param>
        /// <returns></returns>
        public DataSet GetDatasetFromXml(string strXml)
        {
            DataSet dsTemp = new DataSet();
            System.IO.StringReader reader = new System.IO.StringReader(strXml);
            dsTemp.ReadXml(reader);
            return dsTemp;
        }

        /// <summary>
        /// 读取文件返回dataset
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public DataSet GetDatasetFromFile(string strPath)
        {
            string strContent = File.ReadAllText(strPath);
            return GetDatasetFromXml(strContent);
        }

        /// <summary>
        /// 根据各列名和字段值生成sql并执行
        /// </summary>
        /// <param name="drParam">数据列</param>
        /// <param name="strTableName">表名</param>
        /// <param name="strUpdateFlag">更新标志</param>
        /// <returns></returns>
        public void GenerateSqlByFields(DataRow drParam, string strTableName, string strUpdateFlag)
        {
            string strWhere = string.Empty;
            string strRelationSql = string.Empty;//关联表对应sql

            List<string> lstFiledNames = new List<string>();
            List<string> lstFieldValues = new List<string>();
            foreach (DataColumn dcOne in drParam.Table.Columns)
            {
                if (strTableName == "SYS_UNITS")
                {
                    switch (dcOne.ColumnName)
                    {
                        case "id"://主键id
                            lstFiledNames.Add("id");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            strWhere = string.Format(" and id='{0}'", drParam[dcOne.ColumnName]);
                            break;
                        case "unitname":
                            lstFiledNames.Add("unitsname");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unitnameold":
                            lstFiledNames.Add("unitnameold");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "description":
                            lstFiledNames.Add("description1");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "regaddress":
                            lstFiledNames.Add("regaddress");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "regpostcode":
                            lstFiledNames.Add("regpostcode");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "contact":
                            lstFiledNames.Add("contact");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "officeaddress":
                            lstFiledNames.Add("unitsaddress");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "officepostcode":
                            lstFiledNames.Add("postcode");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "telnumber":
                            lstFiledNames.Add("unitstel");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "mobilenumber":
                            lstFiledNames.Add("mobilenumber");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "faxnumber":
                            lstFiledNames.Add("fax");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "email":
                            lstFiledNames.Add("email");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "createdate":
                            lstFiledNames.Add("createdate");
                            string strCreate = string.Format("to_date('{0}','yyyy-mm-dd')", drParam[dcOne.ColumnName]);
                            lstFieldValues.Add(strCreate);
                            break;
                        case "capitalpercentageofinternal":
                            lstFiledNames.Add("capitalpercentageofinternal");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unitmanager":
                            lstFiledNames.Add("unitmanager");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "surveypersonnelcount":
                            lstFiledNames.Add("surveypersonnelcount");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "employeescount":
                            lstFiledNames.Add("employeescount");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "legalpersonname"://组织代码
                            lstFiledNames.Add("ORGANIZATION");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "legalpersoncodeorregcode":
                            lstFiledNames.Add("legalpersoncodeorregcode");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "regcapital":
                            lstFiledNames.Add("regcapital");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "independentunitname":
                            lstFiledNames.Add("independentunitname");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "appendixlist":
                            lstFiledNames.Add("appendixlist");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "prefecture":
                            lstFiledNames.Add("prefecture");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "capitaltype":
                            lstFiledNames.Add("capitaltype");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unittype":
                            lstFiledNames.Add("unittype");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unitproperty":
                            lstFiledNames.Add("unitproperty");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unitactiontypebeforeapply":
                            lstFiledNames.Add("unitactiontypebeforeapply");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "appendixlist3":
                            lstFiledNames.Add("appendixlist3");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "appendixlist4":
                            lstFiledNames.Add("appendixlist4");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "appendixlist5":
                            lstFiledNames.Add("appendixlist5");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "officearea":
                            lstFiledNames.Add("officearea");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "companytype":
                            lstFiledNames.Add("companytype");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "firstqualifyedowmleve":
                            lstFiledNames.Add("firstqualifyedowmleve");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "confidential":
                            lstFiledNames.Add("confidential");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "branchdivision":
                            lstFiledNames.Add("branchdivision");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "legalperson":
                            lstFiledNames.Add("legal");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "surveyleveltype":
                            lstFiledNames.Add("surveyleveltype");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "text":
                            lstFiledNames.Add("text");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "validstart":
                            lstFiledNames.Add("validstart");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "provinid":
                            lstFiledNames.Add("provinid");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "sourceid":
                            lstFiledNames.Add("sourceid");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "datastate":
                            lstFiledNames.Add("datastate");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                    }//switch判断
                }
                else if (strTableName == "SYS_USER")
                {
                    switch (dcOne.ColumnName)
                    {
                        case "userId"://人员结构内码id
                            lstFiledNames.Add("USERID");
                            strWhere = string.Format(" and USERID='{0}'", drParam[dcOne.ColumnName]);
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        //case "username"://目前与userid相同
                        case "name":
                            lstFiledNames.Add("USERNAME");
                            string strUserName = drParam[dcOne.ColumnName].ToString();
                            if(string.IsNullOrEmpty(strUserName))//如果为空则取userid
                            {
                                strUserName = drParam["userId"].ToString();
                            }
                            lstFieldValues.Add(strUserName);
                            break;
                        case "pwd":
                            lstFiledNames.Add("userpwd");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "id":
                            lstFiledNames.Add("id");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "unitbsdtid":
                            lstFiledNames.Add("unitsid");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                        case "appId":
                            lstFiledNames.Add("appId");
                            lstFieldValues.Add(drParam[dcOne.ColumnName].ToString());
                            break;
                    }//switch判断

                }
            }
            string strSql = string.Empty;
            string strFieldName = string.Empty;
            string strFieldValue = string.Empty;
            if (strUpdateFlag == "insert")
            {
                //先执行删除
                if (!string.IsNullOrEmpty(strWhere))
                {
                    strSql = string.Format("delete from {0} where 1=1 {1}", strTableName, strWhere);
                    SysParams.OAConnection().RunSql(strSql);
                }

                for (int p = 0; p < lstFiledNames.Count; p++)
                {
                    strFieldName += string.Format("{0},", lstFiledNames[p]);

                    if (lstFieldValues[p].IndexOf("to_") > -1)
                    {
                        strFieldValue += string.Format("{0},", lstFieldValues[p]);
                    }
                    else
                    {
                        strFieldValue += string.Format("'{0}',", lstFieldValues[p]);
                    }
                }
                strFieldName = strFieldName.Substring(0, strFieldName.Length - 1);
                strFieldValue = strFieldValue.Substring(0, strFieldValue.Length - 1);

                strSql = string.Format("insert into {0}({1}) values({2})", strTableName, strFieldName, strFieldValue);
            }
            else if (strUpdateFlag == "update" && !string.IsNullOrEmpty(strWhere))
            {
                for (int p = 0; p < lstFiledNames.Count; p++)
                {
                    strFieldName += string.Format("{0}='{1}',", lstFiledNames[p], lstFieldValues[p]);
                }
                strFieldName = strFieldName.Substring(0, strFieldName.Length - 1);
                strSql = string.Format("update {0} set {1} where 1=1 {2}", strTableName, strFieldName, strWhere);
            }
            else if (strUpdateFlag == "delete" && !string.IsNullOrEmpty(strWhere))
            {
                strSql = string.Format("delete from {0} where 1=1 {1}", strTableName, strWhere);
            }

            //执行本表操作
            if (!string.IsNullOrEmpty(strSql))
            {
                SysParams.OAConnection().RunSql(strSql);
            }
            //执行关联关系sql
            if (!string.IsNullOrEmpty(strRelationSql))
            {
                SysParams.OAConnection().RunSql(strRelationSql);
            }

        }

        /// <summary>
        /// 获取最大版本号
        /// </summary>
        /// <param name="strInterfaceName">接口名</param>
        /// <returns></returns>
        public string GetMaxVersionId(string strInterfaceName)
        {
            //存储最大版本号
            string strSql = string.Format("select MAX_VERSION from XT_WEBSERVICE where WEBNAME='{0}'",strInterfaceName);
            return SysParams.OAConnection().GetValue(strSql);
        }

        /// <summary>
        /// 更新最大版本号
        /// </summary>
        /// <param name="strMaxVersionId">最大版本号</param>
        /// <param name="strInterfaceName">接口名</param>
        public void UpdateMaxVersionId(string strMaxVersionId, string strInterfaceName)
        {
            //存储最大版本号
            string strSql = string.Format("update XT_WEBSERVICE set MAX_VERSION='{0}' where WEBNAME='{1}'",strMaxVersionId,strInterfaceName);
            SysParams.OAConnection().RunSql(strSql);
        }

        /// <summary>
        /// 分析xml并执行相应的操作
        /// </summary>
        /// <param name="strXml">同步的xml</param>
        /// <param name="strInterfaceName">接口名</param>
        public void AnalyseXml(string strXml, string strInterfaceName)
        {
            try
            {
                DataSet dsReturn = GetDatasetFromXml(strXml);
                if (dsReturn.Tables.Count > 1)//保证内容不为空
                {
                    DataTable dtType = dsReturn.Tables["trans"];
                    DataTable dtContent = dsReturn.Tables["transXml"];

                    if (dtType.Rows.Count > 0)//保证有值
                    {
                        string strFilter = "transType<>'ADD_POST' and transType<>'DELETE_POST'  and transType<>'UPDATE_POST' and transType<>'MERGE_POST' ";
                        DataRow[] drsType = dtType.Select(strFilter, "trans_Id");

                        foreach (DataRow drType in drsType)
                        {
                            strFilter = string.Format("trans_Id='{0}'", drType["trans_Id"]);
                            string strUpdateFlag = drType["transType"].ToString();
                            DataRow[] drsContents = dtContent.Select(strFilter);
                            string strSql = string.Empty;
                            switch (strUpdateFlag.ToUpper())
                            {
                                case "ADD_UNIT":
                                    foreach (DataRow drContent in drsContents)
                                    {
                                        GenerateSqlByFields(drContent, "SYS_UNITS", "insert");
                                    }
                                    break;
                                case "UPDATE_UNIT":
                                    foreach (DataRow drContent in drsContents)
                                    {
                                        GenerateSqlByFields(drContent, "SYS_UNITS", "update");
                                    }
                                    break;
                                case "ADD_USER"://新增用户
                                    foreach (DataRow drContent in drsContents)
                                    {
                                       
                                        GenerateSqlByFields(drContent, "SYS_USER", "insert");
                                    }
                                    break;
                                case "DELETE_USER"://删除用户
                                    foreach (DataRow drContent in drsContents)
                                    {
                                        GenerateSqlByFields(drContent, "SYS_USER", "delete");
                                    }
                                    break;
                                case "UPDATE_USER"://更新用户信息
                                    foreach (DataRow drContent in drsContents)
                                    {
                                        GenerateSqlByFields(drContent, "SYS_USER", "update");
                                    }
                                    break;
                            }
                        }

                        //更新最大版本号
                        if (dtType.Rows.Count > 0)
                        {
                            UpdateMaxVersionId(dtType.Rows[dtType.Rows.Count - 1]["versionId"].ToString(), strInterfaceName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManage.addLogErr("AnalyseXml", ex.Message);
            }
        }

      
    }
}